$(function () {
    $.menuSelector('#system_resource');

    var ztree;
    $('#resource-form').validationEngine({
        'maxErrorsPerField': 1
    });

    var paramsPrefix = function(params) {
        var obj = {};
        $.each(params, function(k, v) {
            obj['resource.' + k] = v;
        });
        return obj;
    };

    $('#save').click(function(e) {
        e.preventDefault();
        var s = '#resource-form';
        if($(s).validationEngine('validate')) {
            var params = $('#resource-form').serializeObject();
            var id = params.id;
            params = paramsPrefix(params);
            alert(JSON.stringify(params));
            $.post(g.ctx + '/system/resource/save', params, function(rets) {
                Ifonly.ApiMessage.process(rets, function (rets) {
                    $('#resource-form-alert').fadeIn(200).fadeOut(2000);
                    _app.clearItem();
                    if (id) {
                        _app.editZNode(rets.data);
                    } else {
                        _app.addZNode(rets.data);
                    }
                });
            });
        }


    });

    var _app = {
        onClick: function(e, treeId, treeNode, clickFlag) {
            var id = treeNode.id;
            if (id != 0) {
                var pNode = treeNode.getParentNode();
                _app.getItem(id, pNode.name);
            } else {
                _app.clearItem();
            }
        },
        addItem: function(treeNode, pid, pname) {
            var $resourceForm = $('#resource-form');
            $resourceForm.find('input[name="pid"]').val(pid);
            $resourceForm.find('input[name="pname"]').val(pname);
        },
        getItem: function(id, pname) {
            $.get(g.ctx + '/system/resource/item/' + id, function(rets) {
                Ifonly.ApiMessage.process(rets, function(rets) {
                    rets.data['pname'] = pname;
                    _app.renderItem(rets.data);
                });
            });
        },
        renderItem: function(item) {
            $.each(item, function(k, v) {
                $('#resource-form').find('*[name="'+ k + '"]').val(v);
            });
        },
        clearItem: function() {
            var $resource = $('#resource-form');
            $resource.find('input[name="id"]').val('');
            $resource.find('input[name="pid"]').val('');
            $resource[0].reset();
        },
        addZNode: function(data) {
            var zTree = $.fn.zTree.getZTreeObj("tree");
            var treeNode = zTree.getNodesByParam("id", data.pid)[0];
            zTree.addNodes(treeNode, {id:data.id, pid:data.pid, name:data.name});
        },
        editZNode: function(data) {
            var zTree = $.fn.zTree.getZTreeObj("tree");
            var treeNode = zTree.getNodesByParam("id", data.id)[0];
            treeNode.name = data.name;
            zTree.updateNode(treeNode, {id:data.id, pid:data.pid, name:data.name});
        },
        beforeRemove: function(treeId, treeNode) {
            Ifonly.Notification.confirm('确认删除资源吗？', function() {
                $.get(g.ctx + '/system/resource/delete/' + treeNode.id, {}, function(rets) {
                    Ifonly.ApiMessage.process(rets, function() {
                        var treeObj = $.fn.zTree.getZTreeObj("tree");
                        treeObj.removeNode(treeNode);
                    }, function() {
                        Ifonly.Notification.alert('删除失败');
                    });
                });
            });
            return false;
        },
        showRemoveBtn: function(treeId, treeNode) {
            return treeNode.id !== 0;
        }
    };

    $.ajax({
        url: g.ctx + '/system/resource/list',
        beforeSend: function () {
            $('#tree').html('正在加载...');
        },
        complete: function () {

        },
        success: function (rets) {
            Ifonly.ApiMessage.process(rets, function (rets) {
                if (rets.data && rets.data.length > 0) {
                    ztree = new ZTree('#tree', {
                        view: {
                            addHoverDom: function(treeId, treeNode) {
                                var sObj = $("#" + treeNode.tId + "_span");
                                if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
                                var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
                                    + "' title='add node' onfocus='this.blur();'></span>";
                                sObj.after(addStr);
                                var btn = $("#addBtn_"+treeNode.tId);
                                if (btn) {
                                    btn.click(function(e) {
                                        e.preventDefault();
                                        e.stopPropagation();
                                        _app.clearItem();
                                        _app.addItem(treeNode, treeNode.id, treeNode.name);
                                    });
                                }
                            },
                            removeHoverDom: function(treeId, treeNode) {
                                $("#addBtn_"+treeNode.tId).unbind().remove();
                            },
                            selectedMulti: false
                        },
                        edit: {
                            enable: true,
                            removeTitle: "",
                            showRenameBtn:false,
                            showRemoveBtn: _app.showRemoveBtn
                        },
                        callback: {
                            onClick: _app.onClick,
                            beforeRemove: _app.beforeRemove
                        }
                    }, rets.data);
                }
            });
        }
    });


});